<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<input id="msg" type="text" />
<button onclick="send()">发送消息</button>
</body>
<script>
    // 连接WebSocket服务器
    const clientId = Math.random().toString(36).substr(2);
    const websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);

    // 监听连接建立成功
    websocket.onopen = function(){
        console.log("WebSocket连接成功......");
    }

    // 监听收到服务端消息
    websocket.onmessage = function(event){
        console.log(event.data);
    }

    // 发送消息
    function send(){
        websocket.send(document.getElementById('msg').value);
    }

    // 监听窗口关闭事件，当窗口关闭时主动去关闭websocket连接
    window.onbeforeunload = function(){
        websocket.close();
    }
</script>
</html>
